package cn.xiyun.xiyuncc.service.impl;

import cn.xiyun.xiyuncc.domain.KillActivity;
import cn.xiyun.xiyuncc.domain.KillCourse;
import cn.xiyun.xiyuncc.exception.OperationException;
import cn.xiyun.xiyuncc.mapper.KillActivityMapper;
import cn.xiyun.xiyuncc.service.IKillActivityService;
import cn.xiyun.xiyuncc.service.IKillCourseService;
import cn.xiyun.xiyuncc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiyun.maple
 * @since 2023-03-25
 */
@Service
public class KillActivityServiceImpl extends ServiceImpl<KillActivityMapper, KillActivity> implements IKillActivityService {
    @Autowired
    private IKillCourseService killCourseService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    /**
     * 课程上架
     * @param id
     */
    @Override
    public void activityOnline(Long id) {
        //根据活动id查询活动
        KillActivity killActivity = super.selectById(id);
        AssertUtil.isNotNull(killActivity,"活动不存在不要搞事情");
        boolean after = new Date().before(killActivity.getEndTime());
        AssertUtil.isTrue(after,"活动已结束请选择其他活动");
        // 查询活动所拥有的商品
        Wrapper<KillCourse> wrapper = new EntityWrapper<>();
        wrapper.eq("activity_id",killActivity.getId());
        List<KillCourse> killCourses = killCourseService.selectList(wrapper);
        AssertUtil.isNotNull(killCourses,"活动商品未加入请加入商品");
        for (KillCourse killCourse : killCourses) {
            // 设置信号量
            RSemaphore semaphore = redissonClient.getSemaphore(killCourse.getId().toString());
            //设置信号量
            boolean setPermitsSuccess = semaphore.trySetPermits(killCourse.getKillCount());
            AssertUtil.isTrue(setPermitsSuccess,"系统异常请稍后重试");
            // 将数据存入redis中
            HashOperations<Object, Object, Object> activityHash = redisTemplate.opsForHash();
            activityHash.put("Activity:"+killActivity.getId().toString(),killCourse.getId().toString(),killCourse);
            // 修改秒杀课程状态
            killCourse.setPublishStatus(KillCourse.COURSE_RELEASED);
            killCourse.setPublishTime(new Date());
            killCourseService.updateById(killCourse);
        }

        // 修改活动状态为已上线
        killActivity.setPublishStatus(KillActivity.ACTIVITY_RELEASED);
        killActivity.setPublishTime(new Date());
        super.updateById(killActivity);

    }
}
